<?php

require_once 'App/MetadataService.php';
require_once 'App/Forms/MetadataForm.php';

class MetadataController extends Zend_Controller_Action
{
	protected $metadataService;
	
	public function preDispatch()
	{
		$this->metadataService = new App_MetadataService();
		$layout = Zend_Layout::getMvcInstance();
		$layout->message = '';
	}
	public function init()
	{
		
	}
	
	public function indexAction()
	{
		
	}
	
	public function addAction()
	{
		$form = new App_Forms_MetadataForm();
		
		if($this->getRequest()->getParam('imageid'))
		{
			$this->view->imageid = $this->getRequest()->getParam('imageid');
		}
		if($this->_request->isPost())
		{
			$postData = $this->getRequest()->getPost();
			$nameCount = 0;
			$valCount = 0;
			$nameArr = array();
			$valArr = array();
			$bad_data = false;
			
			foreach($postData as $key => $data)
			{
				if($data == '')
				{
					$bad_data = true;
					break;
				}
				if($key == 'imageID')
				{
					$imageID = $data;
				}
				else
				{
					$type = substr($key, 0, 4);
					
					if ($type == 'name')
					{
						$nameArr[$nameCount++] = $data;
					}
					if ($type == 'valu')
					{
						$valArr[$valCount++] = $data;
					}
				}
			}
			
			if($bad_data)
			{
				$layout = Zend_Layout::getMvcInstance();
				$layout->message = 'There was an error with the data provided';
				print('bad data received');
				$this->_redirect('index');
			}
			
			for($i = 0; $i < count($nameArr); $i++)
			{
				$this->metadataService->updateMetadata($imageID, $nameArr[$i], $valArr[$i]);
			}
			//$this->metadataService->updateMetadata($postData['imageID'], $postData, $val);
			$layout = Zend_Layout::getMvcInstance();
			$layout->message = 'Attributes successfully added to image.';
			$this->_redirect('index');
		}
		
		$this->view->form = $form;
	}
}